package com.shigen.demo.config;

import com.shigen.demo.entity.User;
import com.shigen.demo.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
@Slf4j
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

  @Resource
  private UserService userService;

  @Override
  public boolean supportsParameter(MethodParameter parameter) {
    return true;
  }

  @Override
  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    String id = request.getParameter("id");
    User user = userService.getById(id);
    log.info("user: {}", user);
    return user;
  }
}
